using MediatR;
using Microsoft.EntityFrameworkCore;
using WMS.Api.Application.Commands.Users;
using WMS.Common;
using WMS.Domain;
using WMS.Infrastructure;

namespace WMS.Api.Application.CommandHandlers.Users
{
    public class GetAllUsersCommandHandler : IRequestHandler<GetAllUsersCommand, ApiResult<List<User>>>
    {
        private readonly IBaseRepository<User> _userRepo;

        public GetAllUsersCommandHandler(IBaseRepository<User> userRepo)
        {
            _userRepo = userRepo;
        }

        public async Task<ApiResult<List<User>>> Handle(GetAllUsersCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<User>> result = new ApiResult<List<User>>("获取所有用户");

            try
            {
                // 获取所有用户并分页
                var query = await _userRepo.GetAllAsync();
                
                var totalCount = query.Count();
                
                var users =  query
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToList();

                result.data = users;
                result.isSuc = true;
                result.msg = $"获取成功，共{totalCount}条记录";
                result.code = StatusCodeEnum.Ok;
            }
            catch (Exception ex)
            {
                result.isSuc = false;
                result.data = null;
                result.msg = $"获取失败：{ex.Message}";
                result.code = StatusCodeEnum.ParamError;
            }

            return result;
        }
    }
} 